package ctm.javacode;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.NamingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class classificationfood {

	private ArrayList<String> foodlist_NotSuit;
	private ArrayList<String> sixfoodtypelist_NotSuit;
	private ArrayList<String> typelist_NotSuit;
	private ArrayList<String> foodlist_Suit;
	private ArrayList<String> sixfoodtypelist_Suit;
	private ArrayList<String> typelist_Suit;
	
	public classificationfood(String ac){
		/*---禁忌食物的List---*/
		foodlist_NotSuit = new ArrayList<String>();
		sixfoodtypelist_NotSuit = new ArrayList<String>();
		typelist_NotSuit = new ArrayList<String>();
		/*---可用食物的List---*/
		foodlist_Suit = new ArrayList<String>();
		sixfoodtypelist_Suit = new ArrayList<String>();
		typelist_Suit = new ArrayList<String>();
		
		dbBean db = new dbBean();

		try {
			db = new dbBean("jdbc/ctmpllab");
			db.Connected();
		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			ArrayList<String> diseas = Parser(ac, db); // 將字串內的病症切成ArrayList
			System.out.print(diseas.toString() + "\n");
			String sql = "select * from diseaseandfood";
			ResultSet rs1 = db.ExcuteQuery(sql);
			// 疾病的禁忌食材
			ArrayList<String> NotSuidfood = new ArrayList<String>(); 
			while (rs1.next()) {
				for (String dis : diseas) {
					if (rs1.getString(dis).equalsIgnoreCase("X")) {
						if (!NotSuidfood.contains(rs1.getString("code")))
							NotSuidfood.add(rs1.getString("code"));
					}

				}
			}
			System.out.print(NotSuidfood.toString() + "\n");
			
			ArrayList<String> physique = Getphysique(ac, db); // 抓取使用者最近測量體質
			System.out.print(physique.toString() + "\n");
			String _sql = "select * from physiqueandfood";
			ResultSet _rs1 = db.ExcuteQuery(_sql);
			// 體質的禁忌食材
			ArrayList<String> physique_Notfood = new ArrayList<String>(); 
			while (_rs1.next()) {
				for (String dis : physique) {
					if (_rs1.getString(dis).equalsIgnoreCase("X")) {
						if (!physique_Notfood.contains(_rs1.getString("attribute")))
							physique_Notfood.add(_rs1.getString("attribute"));
					}
				}
			}
			System.out.print(physique_Notfood.toString() + "\n");
									
			String sqlQuery = "select * from food";
			ResultSet rs2 = db.ExcuteQuery(sqlQuery);
			//挑出禁忌的食物
			while (rs2.next()) {
				if (!FoodSuit(rs2, NotSuidfood , diseas , physique_Notfood ,physique)) {
					/*---禁忌食物---*/
					sixfoodtypelist_NotSuit.add(rs2.getString("sixfoodtype"));
					typelist_NotSuit.add(rs2.getString("type"));
					foodlist_NotSuit.add(rs2.getString("name"));
				}else{
					/*---可用食物---*/
					sixfoodtypelist_Suit.add(rs2.getString("sixfoodtype"));
					typelist_Suit.add(rs2.getString("type"));
					foodlist_Suit.add(rs2.getString("name"));
				}
			} // end while
			db.CloseConn();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	/*---禁忌食物與推薦食物的篩選---*/
	private boolean FoodSuit(ResultSet rs, ArrayList<String> notsuitfood,ArrayList<String> diseas,
			ArrayList<String> physique_Notfood ,ArrayList<String> physique)
			throws NumberFormatException, SQLException {
		if (diseas.contains("G6PD")){ // 蠶豆症
			if (rs.getString("name").contains("蠶豆")) {
				return false;
			}
		}
		
		if (rs.getString("category").contains("、")) {
			String[] category_temp = rs.getString("category").split("、");
			for (String category_str : category_temp) {
				if (notsuitfood.contains(category_str))
					return false;
			}
		} else {
			if (notsuitfood.contains(rs.getString("category")))
				return false;
		}
		
		String coldhot = rs.getString("coldhot");
		if (coldhot.length() > 1){
			char[] t = coldhot.toCharArray();
			for (char physique_str : t) {
				String s = String.valueOf(physique_str);
				if (physique_Notfood.contains(s) == true)
					return false;
			}		
		}	
		if (physique.contains("specialintrinsic")){ // 特稟體質
			if (rs.getString("allergiesfood").contains("自閉禁忌") || rs.getString("allergiesfood").contains("呼吸道過敏") ||	
				rs.getString("allergiesfood").contains("水楊酸類") || rs.getString("allergiesfood").contains("酪蛋白食物") || 
				rs.getString("allergiesfood").contains("色素") || rs.getString("allergiesfood").contains("過敏食物")) 
			{
				return false;
			}
		}
		if (physique.contains("stagnationqi")){ // 氣鬱體質
			if (rs.getString("removalqidepressions").contains("消氣鬱")) {
				return true;
			}
		}
		if (physique.contains("dampnessheat")){ // 濕熱體質
			if (rs.getString("removaldamponessheat").contains("去濕熱")) {
				return true;
			}
		}
		if (physique.contains("phlegmdampness")){ // 痰濕體質
			if (rs.getString("removalphlegmdampness").contains("化痰濕")) {
				return true;
			}
		}
		if (physique.contains("staticblood")){ // 血瘀體質
			if (rs.getString("removalstaticblood").contains("活血化瘀")) {
				return true;
			}
		}
		if (physique.contains("yangdeficiency") || physique.contains("qideficiency")){ // 陽虛體質  || 氣虛體質
			if (rs.getString("enrichyangqi").contains("補氣")) {
				return true;
			}
		}
		if (physique.contains("yindeficiency")){ // 陰虛體質			
			if (rs.getString("enrichyinblood").contains("補血") || rs.getString("enrichyinblood").contains("補陰")) {
				return true;
			}
		}
		return true;
	} // end FoodSuit()
	
	/*---取得體質列表---*/
	private ArrayList<String> Getphysique(String ac, dbBean db) {
		// 檔案讀取
		ArrayList<String> getphysique = new ArrayList<String>();
		ArrayList<String> typeForPrint = new ArrayList<String>();
		String path = "";
		if (ac.contains(";"))
			path = "/" + ac.split(";")[1];
		else
			path = "/" + ac;
		File f = new File("C:/history/general" + path);
		if (f.isDirectory() == false){ // 判斷使用者資料夾是否存在
			typeForPrint.add("平和體質");
			getphysique = correspondphysique(typeForPrint);
		}else{
			String sqlQuery = "";
			if (ac.contains(";"))
				sqlQuery = "SELECT * FROM `questiontable` WHERE identity = '" + ac.split(";")[1] + "'OR account = '"+ac.split(";")[1]+"' order by id desc";
			else
				sqlQuery = "SELECT * FROM `questiontable` WHERE account = '" + ac + "'OR identity='"+ ac +"'order by id desc";
			String filepath = "C:/history/general" + path + "/";		
			try {			
				ResultSet rs = db.ExcuteQuery(sqlQuery);
				rs = db.ExcuteQuery(sqlQuery);
				rs.next();
				filepath = filepath + rs.getString("testtime")+".xml";
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			Document history = null;
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder builder = factory.newDocumentBuilder();
				history = builder.parse(filepath);
			} catch (Exception e) {
				System.out.print("XML analysis error" + e.getMessage());
			}

			Element Body = history.getDocumentElement();
			NodeList TypeNode_t = Body.getElementsByTagName("typePrint");
			Node Type = TypeNode_t.item(0);
			NodeList NumberNode = Type.getChildNodes();

			for (int n = 0; n < NumberNode.getLength(); n++) {
				Node Number = NumberNode.item(n);
				// 儲存使用者的體質
				if (Number.hasChildNodes()) {
					if (Number.getFirstChild().getNodeValue().contains("基本是")) {
						typeForPrint.add(Number.getFirstChild().getNodeValue().substring(3));
					} else if (Number.getFirstChild().getNodeValue().contains("傾向")) {
						typeForPrint.add(Number.getFirstChild().getNodeValue().substring(2));
					} else {
						typeForPrint.add(Number.getFirstChild().getNodeValue());
					}
				}
			}
			
			if (typeForPrint.size() > 2){ //體質超過兩個以上，取得最高前兩個return
				ArrayList<String> typeForPrints = new ArrayList<String>();
				typeForPrints.add(typeForPrint.get(0));
				typeForPrints.add(typeForPrint.get(1));
				getphysique = correspondphysique(typeForPrints);
			}else{
				getphysique = correspondphysique(typeForPrint);
			}
		}
		System.out.println(typeForPrint.toString());
		return getphysique;
	} // end Getphysique()

	private ArrayList<String> correspondphysique(ArrayList<String> physique) {
		ArrayList<String> correspondphysique = new ArrayList<String>();
		/*--體質對應英文--*/
		for (String physique_str : physique) {
			switch (physique_str) {
			case "平和體質":
				correspondphysique.add("moderate");
				break;
			case "氣虛體質":
				correspondphysique.add("qideficiency");
				break;
			case "陽虛體質":
				correspondphysique.add("yangdeficiency");
				break;
			case "陰虛體質":
				correspondphysique.add("yindeficiency");
				break;
			case "血瘀體質":
				correspondphysique.add("staticblood");
				break;
			case "痰濕體質":
				correspondphysique.add("phlegmdampness");
				break;
			case "濕熱體質":
				correspondphysique.add("dampnessheat");
				break;
			case "氣鬱體質":
				correspondphysique.add("stagnationqi");
				break;
			case "特稟體質":
				correspondphysique.add("specialintrinsic");
				break;
			}
		}		
		return correspondphysique;
	} // end correspondphysique()
	
	/*---取得疾病列表---*/
	private ArrayList<String> Parser(String ac, dbBean db)
			throws NamingException, SQLException {
		ArrayList<String> getdiseas = new ArrayList<String>();
		ArrayList<String> diseas = new ArrayList<String>();
		String sqlQuery = "";
		if (ac.contains(";"))
			sqlQuery = "SELECT * FROM `casehistorytable` WHERE account =" + "'" + ac.split(";")[1] + "'";
		else
			sqlQuery = "SELECT * FROM `casehistorytable` WHERE account =" + "'" + ac + "'";
		try {
			ResultSet rs = db.ExcuteQuery(sqlQuery);
			rs = db.ExcuteQuery(sqlQuery);
			rs.next();
			if (rs.getRow() != 0) {
				if (rs.getString("history").contains(",")) {
					String[] diseas_temp = rs.getString("history").split(",");// 多個疾病症狀的切割
					for (String diseas_str : diseas_temp) {
						diseas.add(diseas_str);
					}
				} else {
					if (rs.getString("history").equals(""))// 疾病欄位為空的
						diseas.add("正常人狀態");
					else
						diseas.add(rs.getString("history"));
				}
			}else{
				diseas.add("正常人狀態");
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		System.out.println(diseas.toString());
		getdiseas = corresponddiseas(diseas);
		return getdiseas;
	} // end Parser()
	
	private ArrayList<String> corresponddiseas(ArrayList<String> diseas) {
		ArrayList<String> corresponddiseas = new ArrayList<String>();
		/*--疾病對應英文--*/
		for (String diseas_str : diseas) {
			switch (diseas_str) {
			case "癌症治療中":
				corresponddiseas.add("cancertotreat");
				break;
			case "癌症治癒":
				corresponddiseas.add("cancertocure");
				break;
			case "糖尿病":
				corresponddiseas.add("diabetes");
				break;
			case "腎臟病":
				corresponddiseas.add("kidneydisease");
				break;
			case "高血脂":
				corresponddiseas.add("hyperlipidemia");
				break;
			case "高血壓":
				corresponddiseas.add("hypertension");
				break;
			case "痛風":
				corresponddiseas.add("gout");
				break;
			case "肝炎":
				corresponddiseas.add("hepatitis");
				break;
			case "肝硬化":
				corresponddiseas.add("livercirrhosis");
				break;
			case "慢性肺阻塞":
				corresponddiseas.add("COPD");
				break;
			case "胃炎":
				corresponddiseas.add("gastritis");
				break;
			case "泌尿系統結石":
				corresponddiseas.add("urinarysystemlithiasis");
				break;
			case "中風":
				corresponddiseas.add("stroke");
				break;
			case "甲狀腺機能亢進":
				corresponddiseas.add("hyperthyroidism");
				break;
			case "心臟病":
				corresponddiseas.add("cardiopathy");
				break;
			case "蠶豆症":
				corresponddiseas.add("G6PD");
				break;
			case "膽固醇過高":
				corresponddiseas.add("highcholesterol");
				break;
			case "消化性潰瘍":
				corresponddiseas.add("pepticulcer");
				break;
			case "正常人狀態":
				corresponddiseas.add("Normal");
				break;
			}
		}		
		return corresponddiseas;
	} // end corresponddiseas()
	
	/*---取得禁忌食物列表---*/
	public ArrayList<ArrayList<String>> getnotsuitfood(String str){
		int j = 0;
		ArrayList<String> Notsuitfood = new ArrayList<String>();
		ArrayList<String> Notsuittype = new ArrayList<String>();
		ArrayList<ArrayList<String>> temp = new ArrayList<ArrayList<String>>();
		
		while (j < foodlist_NotSuit.size()) {
			if (sixfoodtypelist_NotSuit.get(j).compareTo(str) == 0){
				Notsuittype.add(typelist_NotSuit.get(j)); //取得六大類的子類別
				Notsuitfood.add(foodlist_NotSuit.get(j)); //取得食物名子
			}			
			j++;
		}
		temp.add(Notsuittype);
		temp.add(Notsuitfood);
		return temp;
	}// end getnotsuitfood()
	
	/*---取得可用食物列表---*/
	public ArrayList<ArrayList<String>> getsuitfood(String str){
		int j = 0;
		ArrayList<String> suitfood = new ArrayList<String>();
		ArrayList<String> suittype = new ArrayList<String>();
		ArrayList<ArrayList<String>> temp = new ArrayList<ArrayList<String>>();
		
		while (j < foodlist_Suit.size()) {
			if (sixfoodtypelist_Suit.get(j).compareTo(str) == 0){
				suittype.add(typelist_Suit.get(j)); //取得六大類的子類別
				suitfood.add(foodlist_Suit.get(j)); //取得食物名子
			}
			j++;
		}
		temp.add(suittype);
		temp.add(suitfood);
		return temp;
	}// end getnotsuitfood()
	
	public String webpublish(ArrayList<ArrayList<String>> data){
		String webpublish = ""; //排版輸出
		String subtypename = ""; //子標題
		ArrayList<String> foodlist = new ArrayList<String>(); //食物列表
		ArrayList<String> typelist = new ArrayList<String>(); //食物六大類列表
		ArrayList<String> typenamelist = new ArrayList<String>();
		int c = 0;
		typelist = data.get(0);
		foodlist = data.get(1);
		for (int i = 0 ; i < typelist.size() ; i++){
			if (!(typenamelist.contains(typelist.get(i))))
				typenamelist.add(typelist.get(i));
		}
		while (c < foodlist.size()) {
			if (typenamelist.contains(typelist.get(c))){
				subtypename = typelist.get(c);
				typenamelist.remove(subtypename);				
				
				webpublish = webpublish + "<div align="+"\"left\""+"><span>"+subtypename+"</span><br></div>";
			}
			if (typelist.get(c).equals(subtypename)){
				if (c == foodlist.size()-1){
					webpublish = webpublish + foodlist.get(c);
				}else{
					if (typelist.get(c+1).equals(subtypename))
						webpublish = webpublish + foodlist.get(c) + "，";
					else
						webpublish = webpublish + foodlist.get(c) + "<br>";
				}
			}
			c++;
		}
		return webpublish;		
	}
}
